#!-*- encoding:utf8 -*-
from django.template import Template, Context, RequestContext
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.contrib.auth.models import User

from osmp.report.models import Report,ReportReceive
from osmp.monitor.models import Monitor
from osmp.users.models import UserProfile
from osmp.host.models import Host
from osmp.util import commom

from django.db.models import Q

from time import sleep
import time,math

def reportlist(request):
    auth_pids = request.session['auth_pids']
    tree = ""  
    tree = commom.creatree(-1, tree, '', '/report/?id=', auth_pids = auth_pids)

    id = request.GET.get('id','-1')
    page = int(request.GET.get("page",1))
    if id == '-1':
        lst_all = Report.objects.filter(mid__pid__in = auth_pids)
    else:
        try:
            lst_all = Report.objects.filter(mid__hid__id = id )
        except:
            raise
            lst_all = []

    (lst, page_lst) = commom.pagination(lst_all, page)

    for l in lst:
        newlist = ReportReceive.objects.filter(rid = l.id).select_related(depth=1)
        l.user = ""
        for n in newlist:
            l.user += n.uid.username + ","
            l.freq = n.freq
    user = UserProfile.objects.all()
    request.session['User'] = user
    request.session['list'] = list
    return render_to_response( "report.html", locals())

def search(request):
    rname = request.POST.get('rname', '')
    uid = request.POST.get('uid', '')
    if 'a' in request.GET:
        name = request.user.username
        uid = request.user.id
        ulist = []
        ridlist = ReportReceive.objects.filter(uid = uid)
        for r in ridlist:
             ulist.append(r.rid.id)
        print ulist
        list = Report.objects.filter(id__in = ulist)
        for l in list:
            newlist = ReportReceive.objects.filter(rid = l.id).select_related(depth=1)
            l.user = ""
            for n in newlist:
                l.user += n.uid.username + ","
                l.freq = n.freq
        user = request.session.get('User')
        return render_to_response("report.html",locals())

    if (not rname or not uid) and not(not rname and not uid):
        
        if rname:
            print rname
            list = Report.objects.filter(rname__contains = rname)
            for l in list:
                newlist = ReportReceive.objects.filter(rid = l.id).select_related(depth=1)
                l.user = ""
                for n in newlist:
                    l.user += n.uid.username + ","
                    l.freq = n.freq
            user = request.session.get('User')
            return render_to_response("report.html",locals())
        
        if uid:
            print uid
            ulist = []
            ridlist = ReportReceive.objects.filter(uid = uid)
            for r in ridlist:
                 ulist.append(r.rid.id)
            print ulist
            list = Report.objects.filter(id__in = ulist)
            for l in list:
                newlist = ReportReceive.objects.filter(rid = l.id).select_related(depth=1)
                l.user = ""
                for n in newlist:
                    l.user += n.uid.username + ","
                    l.freq = n.freq
            user = request.session.get('User')
            return render_to_response("report.html",locals())

    else:
        return HttpResponseRedirect("/report")

def addreport(request):
    errors = []
    messages = []
    if request.method == 'POST':
        if not request.POST.get('rname', ''):
            errors.append('请输入报表名称')
        if not request.POST.get('source', ''):
            errors.append('请输入数据来源')
        if not request.POST.get('mid', ''):
            errors.append('请选择监控目标名称')
        if not request.POST.get('freq',''):
            errors.append('请选择发送周期')
        if not request.POST.get('type',''):
            errors.append('请选择报告类型')
        if not request.POST.getlist('user'):
            errors.append('请选择订阅人')
        if errors:
            list1 = request.session.get('list1')
            list2 = request.session.get('list2')
            return render_to_response("addreport.html", locals())
        if not errors:
            #新增插入操作 - 先存主表
            r = Report.objects.create(
                rname = request.POST.get('rname', ''),
                source = request.POST.get('source', ''),
                mid = Monitor.objects.get(id = request.POST.get('mid', '')),
                type = request.POST.get('type','')
            )
            # - 再存ReportReceive表
            id = r.id
            user = request.POST.getlist('user')
            print len(user)
            for u in user:
                print "+-+-+"
                rr = ReportReceive.objects.create(
                        rid = Report.objects.get(id = id),
                        uid = User.objects.get(id = u),
                        freq = request.POST.get('freq',''),
                )
            #messages.append('添加报表信息成功!!')
            messages.append("addsuccess")
            list1 = request.session.get('list1')
            list2 = request.session.get('list2')
            return render_to_response("addreport.html", locals())
    else:
        list1 = Monitor.objects.all()
        list2 = UserProfile.objects.all()
        request.session['list1'] = list1
        request.session['list2'] = list2
        return render_to_response( "addreport.html", locals())

def modifyrep(request):
    if request.method == 'POST':
        errors = []
        messages = []
        #print id
        if not request.POST.get('rname', ''):
            errors.append('请输入报表名称')
        if not request.POST.get('source', ''):
            errors.append('请输入数据来源')
        if not request.POST.get('mid', ''):
            errors.append('请选择监控目标名称')
        if not request.POST.get('freq',''):
            errors.append('请选择发送周期')
        if not request.POST.get('type',''):
            errors.append('请选择报告类型')
        if not request.POST.getlist('user'):
            errors.append('请选择订阅人')
        if errors:
            id = request.POST.get('id')
            list = Report.objects.filter(id = id)
            list1 = Monitor.objects.all()
            list2 = UserProfile.objects.all()
            return render_to_response("modifyreport.html",locals())
        if not errors:
            #修改 首先清除子表
            id = request.POST.get('id')
            rr = ReportReceive.objects.filter(rid = id)
            rr.delete()
            #修改Report
            r = Report.objects.get(id = id)
            r.rname = request.POST.get('rname', '')
            r.source = request.POST.get('source', '')
            r.mid = Monitor.objects.get(id = request.POST.get('mid', ''))
            r.type = request.POST.get('type','')
            r.save()
            #子表数据重新生成
            id = r.id
            user = request.POST.getlist('user')
            print len(user)
            for u in user:
                print "+-+-+"
                rr = ReportReceive.objects.create(
                        rid = Report.objects.get(id = id),
                        uid = User.objects.get(id = u),
                        freq = request.POST.get('freq',''),
                )
            messages.append("modifysuccess")
            return render_to_response("report.html",{'messages': messages})

def modifyreport(request,id):
    messages = []
    list = Report.objects.get(id = id)
    list1 = Monitor.objects.all()
    list2 = UserProfile.objects.all()
    messages.append("修改状态，请谨慎操作！")
    return render_to_response( "modifyreport.html", locals())

def deletereport(request,id):
    r = Report.objects.filter(id = id)
    rr = ReportReceive.objects.filter(rid = id)
    r.delete()
    rr.delete()
    return HttpResponseRedirect("/report")

def reportinfo(request,id):
    return HttpResponse("monitor project info!!")

def pausereport(request,id):
    return HttpResponse("stop!")

def timecontrol(request):
#    commom.sendmail("yilan_report@baofeng.com","zcq.0@163.com","标题：","内容：")
    while True:
        mailreport()
        sleep(100)

def mailreport(request):
    rr = ReportReceive.objects.all()
    for r in rr:
#        print "%s,%s,%s,%s,%s"%(r.id,r.rid,r.uid.id,r.freq,r.sendtime)
        id = r.id
        user = User.objects.get(id = r.uid.id)
        re = Report.objects.get(id = r.rid.id)
        mid = re.mid.id
        freq = r.freq
        #if not r.sendtime:
        #   r.sendtime = 0
        #sendtime = r.sendtime
        #t = int(time.time()*1000) - int(sendtime)
        t = int(t/1000)
        creatmail(id,1,mid,freq,user.email)
        print "+++++++++++++++"
    print "---------------"

def creatmail(id,t,mid,freq,mail):
    result = ""
    day = 86400
    week = 604800
    month = 2592000
    #根据时差确定是否发送邮件及发送邮件的方式和内容
    if freq == 0:
        if t >= day:
            content = getcontent(freq,mid)
            result = commom.sendmail(mail,"OSMP: Daily Report",content)
    if freq == 1:
        if t >= week:
            content = getcontent(freq,mid)
            result = commom.sendmail(mail,"OSMP: Weekly Report",content)
    if freq == 2:
        if t >= month:
            content = getcontent(freq,mid)
            result = commom.sendmail(mail,"OSMP: Monthly Report",content)
    if result == "success":
        ReportReceive.objects.filter(id=id).update(sendtime = int(time.time()*1000))

def getcontent(freq,mid):
    ""
